package com.cloud.lan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.lan.api.dto.req.LanActivityReq;
import com.cloud.lan.dao.LanActivityMapper;
import com.cloud.lan.dao.LanActivityRecordMapper;
import com.cloud.lan.entity.base.BaseResponse;
import com.cloud.lan.entity.enums.LanActivityStatusEnums;
import com.cloud.lan.entity.model.dataobject.LanActivityDO;
import com.cloud.lan.entity.model.dataobject.LanActivityRecordDO;
import com.cloud.lan.service.ILanActivityService;

import org.springframework.stereotype.Service;

import java.util.List;

import javax.annotation.Resource;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

import static com.cloud.lan.entity.utils.ConstantInterface.Enum.ConstantNumber.FIVE;
import static com.cloud.lan.entity.utils.ConstantInterface.Enum.ConstantNumber.ONE;
import static com.cloud.lan.entity.utils.ConstantInterface.Enum.ConstantNumber.THREE;
import static com.cloud.lan.entity.utils.ConstantInterface.Enum.ConstantNumber.TOW;
import static com.cloud.lan.entity.utils.ConstantInterface.Enum.ConstantNumber.ZERO;

/**
 * <p>
 * 兑换码活动信息表 服务实现类
 * </p>
 *
 * @author xyqierkang@163.com
 * @since 2021-12-23
 */
@Slf4j
@Service
public class LanActivityServiceImpl extends ServiceImpl<LanActivityMapper, LanActivityDO> implements ILanActivityService {

    @Resource
    private LanActivityMapper lanActivityMapper;
    @Resource
    private LanActivityRecordMapper lanActivityRecordMapper;

    @Override
    public BaseResponse manageList(LanActivityReq req) {
        log.info("#查询 兑换码活动 列表 {}", req);
        LambdaQueryWrapper<LanActivityDO> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(LanActivityDO::getCreateTime);
        Page<LanActivityDO> page = new Page<>(req.getPageIndex(), req.getPageSize());
        IPage<LanActivityDO> pageList = lanActivityMapper.selectPage(page, qw);
        pageList.getRecords().forEach(lanActivityDO -> {
            LambdaQueryWrapper<LanActivityRecordDO> larQw = new LambdaQueryWrapper<>();
            larQw.eq(LanActivityRecordDO::getActivityId, lanActivityDO.getId());
            lanActivityDO.setReceiveCount(lanActivityRecordMapper.selectCount(larQw));
            larQw.eq(LanActivityRecordDO::getStatus, ONE.getKey());
            lanActivityDO.setUseCount(lanActivityRecordMapper.selectCount(larQw));
//            List<String> cityNames = JSONUtil.toList(lanActivityDO.getCityName(), String.class);
//            System.out.println(cityNames);
        });
        return BaseResponse.success(pageList);
    }

    @Override
    public BaseResponse add(LanActivityReq req) {
        log.info("#新增 兑换码活动表 {}", req);
        LanActivityDO lanActivityDO = new LanActivityDO();
        BeanUtil.copyProperties(req, lanActivityDO);
        if (ObjectUtil.isNotEmpty(req.getCityNameList())) {
            lanActivityDO.setCityName(JSONUtil.toJsonStr(req.getCityNameList()));
        }
        lanActivityMapper.insert(lanActivityDO);
        return BaseResponse.success();
    }

    @Override
    public BaseResponse delete(String id) {
        log.info("#删除 兑换码活动表 {}", id);
        lanActivityMapper.deleteById(id);
        return BaseResponse.success();
    }

    @Override
    public BaseResponse update(LanActivityReq req) {
        log.info("#更新 兑换码活动表 {}", req);
        // 查询已领取总数
        LambdaQueryWrapper<LanActivityRecordDO> larQw = new LambdaQueryWrapper<>();
        larQw.eq(LanActivityRecordDO::getActivityId, req.getId());
        Integer receiveCount = lanActivityRecordMapper.selectCount(larQw);
        LanActivityDO lanActivityDO = lanActivityMapper.selectById(req.getId());
        if (null != req.getStatus()) {
            // 更新上下架逻辑
            lanActivityDO.setStatus(req.getStatus());
            lanActivityMapper.updateById(lanActivityDO);
            return BaseResponse.success();
        }
        BeanUtil.copyProperties(req, lanActivityDO, "status");
        // 需要修改的总数和已领取总数实时比较
        if (!req.getAcType().equals(FIVE.getKey()) && (req.getAcCount() < receiveCount)) {
            // 说明修改的总数小于已领取总数，这里需要按照目前已领取总数更新
            log.info("#更新 修改小于已领取总数 要修改数量：{} , 目前已经领取数量：{}", req.getAcCount(), receiveCount);
            req.setAcCount(receiveCount);
        }

        if (lanActivityDO.getStatus().equals(LanActivityStatusEnums.THREE.getId())) {
            // 判断劵的到期时间是否大于当前时间
            if (DateUtil.compare(lanActivityDO.getEndTime(), DateUtil.date()) > ZERO.getKey()) {
                lanActivityDO.setStatus(LanActivityStatusEnums.TOW.getId());
            }
        }
        // 判断劵的到期时间是否小于当前时间
        if (DateUtil.compare(lanActivityDO.getEndTime(), DateUtil.date()) < ZERO.getKey()) {
            lanActivityDO.setStatus(LanActivityStatusEnums.THREE.getId());
        }
        if (ObjectUtil.isNotEmpty(req.getCityNameList())) {
            lanActivityDO.setCityName(JSONUtil.toJsonStr(req.getCityNameList()));
        }
        lanActivityMapper.updateById(lanActivityDO);
        return BaseResponse.success();
    }

    @Override
    public void adjustActivity() {
        log.info("#adjustActivity 开始调整兑换码 ");
        LambdaQueryWrapper<LanActivityDO> qw = new LambdaQueryWrapper<>();
        qw.in(LanActivityDO::getStatus, ONE.getKey(), TOW.getKey());
        List<LanActivityDO> lanActivityDOList = lanActivityMapper.selectList(qw);
        lanActivityDOList.forEach(list -> {
            // 查询劵是否失效了
            if (DateUtil.compare(list.getEndTime(), DateUtil.date()) < ZERO.getKey()) {
                list.setStatus(THREE.getKey());
                log.info("#adjustActivity 已失效 {} ", list.getId());
                lanActivityMapper.updateById(list);
            }
        });
    }
}
